<?php
/**
 * Created by PhpStorm.
 * User: kiki
 * Date: 2022/6/16
 */

namespace App\Common\Service\Tool;

use App\Common\Service\BaseService;
use EasySwoole\Jwt\Jwt as BaseJwt;
use Mine\Exception\NormalStatusException;
use Mine\Helper\MineCode;
use Psr\Container\ContainerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;

class JwtService extends BaseService
{

    public $userId;

   // public static int $time = 604800; // 过期时间(1周)

    protected static string $secretKey = 'sadsrt34456q34mHDY';

   // public function __construct(ContainerInterface $container)
   // {
   //     $this->container = $container;
   //     $this->response = $container->get(ResponseInterface::class);
   // }

    public function token($userId = ''): array
    {
        $jwtObject = BaseJwt::getInstance()
        // ->setSecretKey(self::$secretKey)// 秘钥
            ->publish();

        $jwtObject->setAlg('HMACSHA256'); // 加密方式
        $jwtObject->setAud($userId); // 用户
        $jwtObject->setExp(time() + config('jwt.ttl')); // 过期时间
        $jwtObject->setIat(time()); // 发布时间
        $jwtObject->setIss('grace'); // 发行人
        $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
        // $jwtObject->setNbf(time()+60*5); // 在此之前不可用
        $jwtObject->setSub('grace-api-token'); // 主题

        // 自定义数据
        $jwtObject->setData([
            'other_info'
        ]);

        // 最终生成的token
        $token = $jwtObject->__toString();

        return ['token' => $token, 'token_expire_time' => config('jwt.ttl')];
    }

    public function getUserIdByToken($token)
    {
        try {
            $jwtObject = BaseJwt::getInstance()->decode($token);

            // 如果encode设置了秘钥,decode 的时候要指定
            // $status = $jwtObject->setSecretKey(self::$secretKey)->decode($token);
            $status = $jwtObject->getStatus();;

            switch ($status) {
                case  1:
                    echo '验证通过';
                    $this->userId = $jwtObject->getAud();
                    return $this->userId;
                    break;
                case  -1:
                case  -2:
                    throw new NormalStatusException('请先登录', MineCode::TOKEN_EXPIRED);
                    break;
            }
        } catch (\EasySwoole\Jwt\Exception $e) {
            throw new NormalStatusException('jwt验证出错1', MineCode::TOKEN_EXPIRED);
        }
    }

    /**
     * 通过token获取用户数据(用于刚登录时)
     * @param $token
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|null|object
     */
    public function user($token)
    {
        $userId = $this->getUserIdByToken($token);

        return (new User())->getInfo('id', $userId);
    }

    /**
     * 接口请求时，全局用户数据
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|null|object
     */
    public function userInfo()
    {
        if (empty($this->userId)) {
            return $this->error('暂未登录，请登录后重试');
        }

        return (new User())->getInfo('id', $this->userId);
    }
}